<?php
namespace common\models;
use Yii;

/**
 * 功能:公共的一些方法
 *
 * @property integer $id
 * @property string $brand_name
 * @property integer $valid
 */
class Common {
	/**
	 * 功能:去掉数组中null
	 */
	public static function remove_null($arr) {
		$new_arr = array();
		foreach ($arr as $k => $v) {
			if (!isset($v) or $v == '') {
				$new_arr[$k] = '';
			} else {
				$new_arr[$k] = $v;
			}
		}
		return $new_arr;
	}
	/**
	 * 文件功能:上传客户头像
	 * 把照片和站id联系起来，保存到images目录下，web访问地址插入数据库.
	 * 参数：图片地址
	 * 返回值：成功，返回web可以访问的页面地址；失败，返回空字符串
	 */
	public static function uploadHeadImage() {
		//上传图片的处理
		$uploadImgFilePath = \Yii::$app->params['uploadImageFilepath'];
		$headImageFilepath = $uploadImgFilePath . '/head_image/'; //用户头像的路径,服务器上对应的路径
		if (count($_FILES) == 0) {
			\Yii::$app->utils->apiLog(basename(__FILE__) . '===' . ', in upload_photo, file extend name is invalid, uploaded filename: ' . $_FILES['file']['name'], $module = '');
			return '';
		}
		//上传文件，每月存放一个目录
		$month = date('Y-m');
		$upload_filepath = $headImageFilepath . '/' . $month . '/';
		if (!file_exists($upload_filepath)) {
			if (!mkdir($upload_filepath)) {
				\Yii::$app->utils->apiLog(basename(__FILE__) . '===' . ', in upload_photo, mkdir failed. upload_filepath:  ' . $upload_filepath, $module = '');
				return '';
			}
		}
		$filename = self::generateRandstr(10) . '.' . pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION); // filename
		\Yii::$app->utils->apiLog(basename(__FILE__) . '===' . ", filename: $filename", $module = '');
		//检查文件的扩展名是否合法。jpg gif png
		$fiearr = explode(".", $filename); //将原文件名分成数组
		$fie_extend = strtolower($fiearr[count($fiearr) - 1]); //列出上传文件的扩展名
		if ($fie_extend == "jpg" || $fie_extend == "gif" || $fie_extend == "png") {
			//移动图片到images目录下
			if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_filepath . $filename)) {
				// move succeeded
				//api_log( 'file upload succeeded, filename: ' . basename( $_FILES['file']['name'] ) . '.' . $_FILES['file']['type'] );
				return $month . '/' . $filename;
			} else {
				\Yii::$app->utils->apiLog(basename(__FILE__) . '===' . ", in upload_photo, move file failed: ", $module = '');
				return '';
			}
		} else {
			\Yii::$app->utils->apiLog(basename(__FILE__) . '===' . ", in upload_photo, file extend name is invalid, uploaded filename: " . $_FILES['file']['name'], $module = '');
			return '';
		}
	}
	/**
	 * 功能:保存照片
	 */
	function savePic($picInfo, $dirPrefix, $userid) {
		//上传图片的处理
		$uploadImgFilePath = \Yii::$app->params['uploadImageFilepath'];
		$doc_root = $uploadImgFilePath;
		try {
			// Undefined | Multiple Files | $_FILES Corruption Attack
			// If this request falls under any of them, treat it invalid.
			if (!isset($picInfo['error']) || is_array($picInfo['error'])) {
				throw new RuntimeException('Invalid parameters.');
			}
			// Check $fileInfo['error'] value.
			switch ($picInfo['error']) {
			case UPLOAD_ERR_OK:
				break;
			case UPLOAD_ERR_NO_FILE:
				throw new RuntimeException('No file sent.');
			case UPLOAD_ERR_INI_SIZE:
			case UPLOAD_ERR_FORM_SIZE:
				throw new RuntimeException('Exceeded filesize limit.');
			default:
				throw new RuntimeException('Unknown errors.');
			}
			// You should also check filesize here.
			if ($picInfo['size'] > 10 * 1024 * 1024) {
				throw new RuntimeException('Exceeded filesize limit.');
			}
			// DO NOT TRUST $fileInfo['mime'] VALUE !!
			// Check MIME Type by yourself.
			$finfo = new \finfo(FILEINFO_MIME_TYPE);
			if (false === $ext = array_search($finfo->file($picInfo['tmp_name']), array('jpg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif'), true)) {
				throw new RuntimeException('Invalid file format.');
			}
			//上传文件，每月存放一个目录
			$dir = $dirPrefix . date('Y-m');
			//$upload_filepath = $image_filepath . $dir . '/';
			$upload_filepath = $doc_root . '/' . $dirPrefix . '/' . $dir . '/';
			if (!file_exists($upload_filepath)) {
				if (!mkdir($upload_filepath)) {
					throw new RuntimeException('in upload_photo, mkdir failed. upload_filepath: ' . $upload_filepath);
				}
			}
			$filename = time() . \common\models\Common::generateRandstr(4) . $userid . $picInfo['name'];
			// You should name it uniquely.
			// DO NOT USE $fileInfo['name'] WITHOUT ANY VALIDATION !!
			// On this example, obtain safe unique name from its binary data.
			if (!move_uploaded_file($picInfo['tmp_name'], sprintf($upload_filepath . '%s', $filename))) {
				throw new RuntimeException('Failed to move uploaded file.');
			}
			return $dir . '/' . $filename;
		} catch (RuntimeException $e) {
			return '';
		}
	}
	/**
	 * 功能;生成随机码
	 */
	public static function generateRandstr($length) {
		// 密码字符集，可任意添加你需要的字符
		$chars = 'abcdefghjklmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
		$randstr = '';
		for ($i = 0; $i < $length; $i++) {
			// 这里提供两种字符获取方式
			// 第一种是使用 substr 截取$chars中的任意一位字符；
			// 第二种是取字符数组 $chars 的任意元素
			// $randstr .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
			$randstr .= $chars[mt_rand(0, strlen($chars) - 1)];
		}
		return $randstr;
	}
	/**
	 * 文件功能:上传用车的照片
	 * 思路:照片是一张一张上传的,有对应关系的,所以存储通过带有索引的数据 json_encode 后来存储
	 * 参数：图片地址
	 * 返回值：成功，返回web可以访问的页面地址；失败，返回空字符串
	 */
	public static function uploadUseCarImage($uploadImgFilePath, $prefix) {
		//上传图片的处理
		$headImageFilepath = $uploadImgFilePath . $prefix; //用户用车的图片,服务器上对应的路径
		if (count($_FILES) == 0) {
			\Yii::$app->utils->apiLog(basename(__FILE__) . '===' . ', in upload_photo, file extend name is invalid, uploaded filename: ' . $_FILES['file']['name'], $module = '');
			return '';
		}
		//上传文件，每月存放一个目录
		$month = date('Y-m');
		$upload_filepath = $headImageFilepath . '/' . $month . '/';
		if (!file_exists($upload_filepath)) {
			if (!mkdir($upload_filepath)) {
				\Yii::$app->utils->apiLog(basename(__FILE__) . '===' . ', in upload_photo, mkdir failed. upload_filepath:  ' . $upload_filepath, $module = '');
				return '';
			}
		}
		$filename = self::generateRandstr(10) . '.' . pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION); // filename
		\Yii::$app->utils->apiLog(basename(__FILE__) . '===' . ", filename: $filename", $module = '');
		//检查文件的扩展名是否合法。jpg gif png
		$fiearr = explode(".", $filename); //将原文件名分成数组
		$fie_extend = strtolower($fiearr[count($fiearr) - 1]); //列出上传文件的扩展名
		if ($fie_extend == "jpg" || $fie_extend == "gif" || $fie_extend == "png") {
			//移动图片到images目录下
			if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_filepath . $filename)) {
				// move succeeded
				//api_log( 'file upload succeeded, filename: ' . basename( $_FILES['file']['name'] ) . '.' . $_FILES['file']['type'] );
				return $month . '/' . $filename;
			} else {
				\Yii::$app->utils->apiLog(basename(__FILE__) . '===' . ", in upload_photo, move file failed: ", $module = '');
				return '';
			}
		} else {
			\Yii::$app->utils->apiLog(basename(__FILE__) . '===' . ", in upload_photo, file extend name is invalid, uploaded filename: " . $_FILES['file']['name'], $module = '');
			return '';
		}
	}
	/**
	 * 功能:保存h5上传上来的base64的代码为图片格式
	 */
	public static function saveBase64ToPic($pic_string, $uploadImgFilePath, $prefix) {
		//上传图片的处理
		$headImageFilepath = $uploadImgFilePath . $prefix; //用户用车的图片,服务器上对应的路径
		if (empty($pic_string)) {
			\Yii::$app->utils->apiLog(basename(__FILE__) . '===' . ', h5 , in upload_photo, file extend name is invalid, uploaded filename: ' . $_FILES['file']['name'], $module = '');
			return '';
		}
		//上传文件，每月存放一个目录
		$month = date('Y-m');
		$upload_filepath = $headImageFilepath . '/' . $month . '/';
		if (!file_exists($upload_filepath)) {
			if (!mkdir($upload_filepath)) {
				\Yii::$app->utils->apiLog(basename(__FILE__) . '===' . ', h5 ,in upload_photo, mkdir failed. upload_filepath:  ' . $upload_filepath, $module = '');
				return '';
			}
		}
		$filename = 'h5_' . self::generateRandstr(7) . '.jpg'; // filename
		\Yii::$app->utils->apiLog(basename(__FILE__) . '===' . ", filename: $filename", $module = '');
		//检查文件的扩展名是否合法。jpg gif png
		$fiearr = explode(".", $filename); //将原文件名分成数组
		if (1) {
			//移动图片到images目录下
			$IMG = base64_decode(str_replace('data:image/jpeg;base64,', '', $pic_string));
			if (file_put_contents($upload_filepath . $filename, $IMG)) {
				\Yii::$app->utils->apiLog(basename(__FILE__) . '===' . ", in base64 save file success: ", $module = '');
				return $month . '/' . $filename;
			} else {
				\Yii::$app->utils->apiLog(basename(__FILE__) . '===' . ",  in base64 save file failed: ", $module = '');
				return '';
			}
		} else {
			\Yii::$app->utils->apiLog(basename(__FILE__) . '===' . ", in  in base64 save file, uploaded filename: " . $_FILES['file']['name'], $module = '');
			return '';
		}
	}
	/**
	 * 功能:拆分字符串
	 */
	public static function splitString($string, $separate) {
		return explode($separate, $string);
	}

	/**
	 * 文件功能:文件上传
	 * 思路:文件是一张一张上传的,有对应关系的,所以存储通过带有索引的数据 json_encode 后来存储
	 * 参数：图片地址
	 * 返回值：成功，返回web可以访问的页面地址；失败，返回空字符串
	 */
	public static function uploadFiles($uploadImgFilePath, $prefix,$fileName='file') {
		//上传图片的处理
		$headImageFilepath = $uploadImgFilePath . $prefix; //用户用车的图片,服务器上对应的路径

		if (count($_FILES) == 0) {
			\Yii::$app->utils->apiLog(basename(__FILE__) . '===' . ', in upload_file, file extend name is invalid, uploaded filename: ' . $_FILES[$fileName]['name'], $module = '');
			return '';
		}

		//上传文件，每月存放一个目录
		$month = date('Y-m');
		$upload_filepath = $headImageFilepath . '/' . $month . '/';
		if (!file_exists($upload_filepath)) {
			if (!mkdir($upload_filepath)) {
				\Yii::$app->utils->apiLog(basename(__FILE__) . '===' . ', in upload_file, mkdir failed. upload_filepath:  ' . $upload_filepath, $module = '');
				return '';
			}
		}
		$filename = self::generateRandstr(10) . '.' . pathinfo($_FILES[$fileName]['name'], PATHINFO_EXTENSION); // filename
		\Yii::$app->utils->apiLog(basename(__FILE__) . '===' . ", filename: $filename", $module = '');

		//检查文件的扩展名是否合法。jpg gif png
		$fiearr = explode(".", $filename); //将原文件名分成数组
		$fie_extend = strtolower($fiearr[count($fiearr) - 1]); //列出上传文件的扩展名
		if ($fie_extend == "jpg" || $fie_extend == "gif" || $fie_extend == "png" || $fie_extend == "xlsx" || $fie_extend == "xls" || $fie_extend == "doc" || $fie_extend == "docx") {

			if (move_uploaded_file($_FILES[$fileName]['tmp_name'], $upload_filepath . $filename)) {
				// move succeeded
				\Yii::$app->utils->apiLog('file upload succeeded, filename: ' . basename($_FILES[$fileName]['name']) . '.' . $_FILES[$fileName]['type']);
				$fileRealname = $_FILES[$fileName]['name'];
				return ['name' => $fileRealname, 'path' => $month . '/' . $filename];
			} else {
				\Yii::$app->utils->apiLog(basename(__FILE__) . '===' . ", in upload_file, move file failed: ", $module = '');
				return [];
			}
		} else {
			\Yii::$app->utils->apiLog(basename(__FILE__) . '===' . ", in upload_file, file extend name is invalid, uploaded filename: " . $_FILES['file']['name'], $module = '');
			return [];
		}
	}
}
